package tron

import (
	"context"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/gcache"
	"time"
	"tronServer/internal/model/domain"
	"tronServer/utility/tron"

	"tronServer/api/tron/v1"
)

// TrxTransfer trx 转账
func (c *ControllerV1) TrxTransfer(ctx context.Context, req *v1.TrxTransferReq) (res *v1.TrxTransferRes, err error) {
	var (
		txId     string
		setState bool
	)
	// 唯一校验
	{
		if setState, err = gcache.SetIfNotExist(ctx, req.UniqueId, gjson.New(req), time.Minute*10); err != nil {
			return
		}
		if !setState {
			err = gerror.New("Trx 转账失败、编号重复")
			return
		}
	}

	// 开始转账
	{
		if txId, err = tron.Transaction.Trx(ctx, &domain.TronTransactionDetail{
			From:    req.From,
			To:      req.To,
			Amount:  req.Amount,
			HashKey: req.HashKey,
		}); err != nil {
			return
		}
	}
	// 返回数据
	{
		res = &v1.TrxTransferRes{
			TxId: txId,
		}
	}
	return
}
